import React, { useEffect, useState, useRef } from "react"
import classNames from 'classnames'
import HeaderNav from "@/components/header-nav"
import styles from "./index.module.less"
import { Empty, Button } from 'antd-mobile'
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { getInvited , getCommonSettingsByKeys, getUserInfo} = $globalServicer('My')

// 模拟API调用，实际项目中需要替换为真实的API


const Inviter = () => {
  const [invitedCount, setInvitedCount] = useState(0)
  const [records, setRecords] = useState([])
  const [loading, setLoading] = useState(false)
  const [noData, setNoData] = useState(false)
  const [inviteDesc, setInviteDesc] = useState('')
  const [userInfo, setUserInfo] = useState(null)
  const [inviteUrl, setInviteUrl] = useState('')

  // 复制链接功能
  const handleCopy = async () => {
    if (!inviteUrl) {
      showErrorToast("邀请链接生成失败，请稍后再试")
      return
    }

    const copyStr = inviteUrl + ' 分享好友立即注册获得奖励'
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(copyStr)
        showSuccessToast('复制成功')
      } else {
        // 降级处理
        const textArea = document.createElement('textarea')
        textArea.value = copyStr
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        showSuccessToast('复制成功')
      }
    } catch (err) {
      showErrorToast("复制失败，请手动复制")
    }
  }

  // 获取用户信息并生成邀请链接
  const fetchUserInfo = () => {
    getUserInfo().then(res => {
      let url = window.location.href.split('#')[0] + '#/register?invite_code=' + res?.user?.id
      setInviteUrl(url)
      setUserInfo(res)
    })
  }

  // 初始化数据加载
  useEffect(() => {
    const initializeData = async () => {
      try {
        setLoading(true)
        const response = await getInvited()
        setInvitedCount(response.count)
        setRecords(response.list)
          console.log(response,'response')

        setNoData(response.list.length === 0)
      } catch (error) {
        showErrorToast("加载失败，请稍后再试")
      } finally {
        setLoading(false)
      }
    }
    const getSettings = async () => {
      const response = await getCommonSettingsByKeys('inviter_desc')
      console.log(response,'response')
      setInviteDesc(response.value.toString())
    }

    initializeData()
    getSettings()
    fetchUserInfo()
  }, [])


  return (
    <div className={styles.inviterWrap}>
      <div className="header">
        <HeaderNav title="邀请有礼" backArrow={true} />
      </div>
      
      <div 
        className={styles.container}
        style={{ height: 'calc(100vh - 45px)', overflowY: 'auto' }}
      >
        {/* 邀请链接区域 */}
        <div className={styles.inviteLinkSection}>
          <div className={styles.backgroundImage}></div>
          <div className={styles.inviteContent}>
            <h2 className={styles.inviteTitle}>邀请好友，共享收益</h2>
            <p className={styles.inviteSubtitle}>每成功邀请一位好友，即可获得丰厚奖励</p>
            <div className={styles.inviteLinkBox}>
              <p className={styles.linkLabel}>我的专属邀请链接</p>
              <p className={styles.inviteLink}>{inviteUrl || '正在生成邀请链接...'}</p>
                <Button
                    className={styles.copyButton}
                    onClick={handleCopy}
                    disabled={!inviteUrl}
                >
                    <div className={styles.copyButtonFlex}>
                        <span className={styles.chevronIconCopy}>content_copy</span>
                        <span className={styles.copyButtontitle}>一键复制</span>
                    </div>
                </Button>
            </div>
          </div>
        </div>

          {/* 奖励说明区域 */}
          <div className={styles.rewardSection}>
          <div className={styles.rewardCard}>
            <h3 className={styles.rewardTitle}>邀请规则</h3>
            <div className={styles.rewardList}>
                <div className={styles.rewardItem}>
                    <div className={styles.chevronIconON}>monetization_on</div>
                    <div className={styles.rewardContent}>
                        <div 
                          className={styles.rewardItemDesc}
                          dangerouslySetInnerHTML={{ __html: inviteDesc || '正在加载邀请规则...' }}
                        />
                    </div>
                </div>
            </div>
          </div>
          </div>

          {/* 邀请记录区域 */}
        <div className={styles.recordsSection}>
          <div className={styles.recordsHeader}>
            <h3 className={styles.recordsTitle}>邀请记录</h3>
            <span className={styles.recordsCount}>已邀请 {invitedCount} 人</span>
          </div>
          <div className={styles.recordsList}>
            {records.map((record) => (
              <div key={record.id} className={styles.recordItem}>
                <div className={styles.recordAvatar}>
                  <img src={record.cover || 'https://via.placeholder.com/48'} alt={record.name} />
                </div>
                <div className={styles.recordInfo}>
                  <div className={styles.recordName}>{record.name}</div>
                  <div className={styles.recordDate}>{record.created_at}</div>
                </div>
              </div>
            ))}
            {noData && <div className={styles.emptyContainer}><Empty description='暂无邀请记录' /></div>}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Inviter;
